﻿using System;
using System.Collections.Generic;
using System.Windows.Controls;
using LantinxShare.LBS.Location;
using Com.Mapabc.Maps.Api.Events;
using Com.Mapabc.Maps.Api.BaseTypes;
using LantinxLBS.Common;
using System.Diagnostics;
using LantinxLBS.Views;
using Com.Mapabc.Maps.Api.Overlays;
using Com.Mapabc.Maps.Api.Styles;
using Com.Mapabc.Maps.Core.Util;
using Com.Mapabc.Maps.Api.Enums;
using System.Collections.ObjectModel;
using System.Windows;
using LantinxShare.Common;
using LantinxShare.LBS;

namespace LantinxLBS
{
    public partial class MainPage : UserControl
    {
        private ObservableCollection<GMark> overList = new ObservableCollection<GMark>();
        //private List<GLocation> list = new List<GLocation>();
        //private double amendedLatitude = -0.002;
        //private double amendedLongtude = 0.004;
        //private bool isAmendedb = false;

        private String downLoadURL = string.Empty;
        private bool isLoadMark = false;
        public MainPage()
        {
            InitializeComponent();
            this.map.Map_Loaded += MainPage_Loaded;
            this.lstMarks.ItemsSource = overList;
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);
        }

        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            LoadUser();
        }

        #region 点击地图
        public void MainPage_Loaded(object obj, MapEventArgs args)
        {
            map.Mouse_Click += Map_MouseClick;
            map.Add_Overlay += new EventHandler<MapEventArgs>(map_Add_Overlay);
            LoadMarks();
        }


        private void Map_MouseClick(object obj, MapMouseEventArgs args)
        {
            // xy = args.CenterXY;
            //LngX.Text = xy.X.ToString();
            //LatY.Text = xy.Y.ToString();
            //if (isMark)
            //{
            //    DrawCircle(args.CenterXY);
            //}
        }

        #endregion
        #region DrawCircle


        void map_Add_Overlay(object sender, MapEventArgs e)
        {
            var list = map.GetOverlaysByType(MOverlayType.MCircle);
            if (list.Count > 0 && this.btnAddMarks.IsChecked.Value && !isLoadMark)
            {
                foreach (var item in list)
                {
                    var circle = item as MCircle;
                    if (circle != null)
                    {

                        if (circle.Tag == null)
                        {
                            //插入标注成功后，从服务器取回ID更新当前GMark对象,同时更新当前维护的标注列表
                            FrmAddMark frmAdd = new FrmAddMark();
                            frmAdd.Show();
                            frmAdd.SetCircle(circle, map, (obj, gmarkObj) =>
                            {
                                DrawACircle(obj, gmarkObj);
                                overList.Add(gmarkObj);
                            });
                            map.SetCurrentMouseTool(MMapMouseTools.PanWheelZoom);
                            this.btnAddMarks.IsChecked = false;
                        }
                        else
                        {
                        }
                    }
                }
            }
        }

        private void DrawACircle(MCircle circle, GMark gmark)
        {

            circle.Tip = MapHelper.GetMTip(gmark.MarkName, gmark.Address, gmark.Description);

            circle.Tag = new ShapeEx() { IsAddEvent = true, Mark = gmark };
            circle.MouseLeftButtonDown += (o, e1) =>
            {

            };

            circle.FillStyle = getMFillStyle();
            circle.LineStyle = getMLineStyle();
            circle.CanShowTip = true;
        }

        private MLineStyle getMLineStyle()
        {
            MLineStyle LineStyle = new MLineStyle()
            {
                Color = Utilities.HexToColor("#046788"),
                Thickness = int.Parse("5"),
            };
            return LineStyle;
        }
        private MFillStyle getMFillStyle()
        {
            MFillStyle FillStyle = new MFillStyle()
            {
                Color = Utilities.HexToColor("#5cb4d1"),
                Opacity = float.Parse("0.8"),
            };
            return FillStyle;
        }
        #endregion
        #region
        private void btnRole_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            FrmRole2 frmRole = new FrmRole2();
            frmRole.CloseInvoke(() =>
            {
                LoadUser();
            });
            frmRole.Show();
        }

        private void LoadUser()
        {
            DataHelper.LoadUser((result) =>
            {
                this.Dispatcher.BeginInvoke(() =>
                {
                    this.cmbUser.ItemsSource = result;
                });

            });
        }

        private void AddMarks_Click(object sender, System.Windows.RoutedEventArgs e)
        {

            if (this.btnAddMarks.IsChecked.Value)
            {
                map.SetCurrentMouseTool(MMapMouseTools.DrawCircle);
            }
            else
            {
                map.SetCurrentMouseTool(MMapMouseTools.PanWheelZoom);

            }
        }
        #endregion

        private void LoadMarks()
        {
            DataHelper.LoadMark((result) =>
            {

                this.Dispatcher.BeginInvoke(() =>
                {
                    //this.cmbList.ItemsSource = roleList;
                    isLoadMark = true;
                    foreach (var item in result)
                    {
                        overList.Add(item);
                        MCircle circle = new MCircle(new MLngLat(G.CLongitude(item.Longitude), G.CLatitude(item.Latitude)), item.Radius);

                        DrawACircle(circle, item);

                        this.map.AddOverlay(circle, false);
                    }

                    isLoadMark = false;
                });

            });
            #region
            /*
            PathHelper.GetData("AddressPage.aspx?option=" + GConstant.OP_GET_MARK, (e) =>
            {
                List<GMark> roleList = new List<GMark>();
                List<string[]> list = e.ResultList;

                foreach (var item in list)
                {
                    roleList.Add(new GMark()
                    {
                        Id = int.Parse(item[0]),
                        MarkName = item[1],
                        Address = item[2],
                        Description = item[3],
                        Longitude = double.Parse(item[4]),
                        Latitude = double.Parse(item[5]),
                        Altitude = double.Parse(item[6]),
                        Radius = double.Parse(item[7]),
                        West = double.Parse(item[8]),
                        South = double.Parse(item[9]),
                        East = double.Parse(item[10]),
                        North = double.Parse(item[11])
                    });
                }

                this.Dispatcher.BeginInvoke(() =>
                {
                    //this.cmbList.ItemsSource = roleList;
                    isLoadMark = true;
                    foreach (var item in roleList)
                    {
                        overList.Add(item);
                        MCircle circle = new MCircle(new MLngLat(G.CLongitude(item.Longitude), G.CLatitude(item.Latitude)), item.Radius);

                        DrawACircle(circle, item);

                        this.map.AddOverlay(circle, false);
                    }

                    isLoadMark = false;
                });
            });*/
            #endregion
        }

        private void TextBlock_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            GMark gmark = this.lstMarks.SelectedItem as GMark;
            if (gmark != null)
            {
                map.SetZoomAndCenter(17, new MLngLat(G.CLongitude(gmark.Longitude), G.CLatitude(gmark.Latitude)));
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            var btnCurrent = sender as Button;
            GMark gmark = btnCurrent.Tag as GMark;
            if (gmark != null)
            {
                PathHelper.GetData("AddressPage.aspx?option=" + GConstant.OP_DEL_MARK,
                        new Dictionary<string, string>(){
                {"id",gmark.Id.ToString()}
                }, (e1) =>
                    {
                        this.Dispatcher.BeginInvoke(() =>
                        {
                            var overlayList = this.map.GetOverlaysByType(MOverlayType.MCircle);
                            MCircle circle = null; ;
                            foreach (var item in overlayList)
                            {
                                var temp = item as MCircle;
                                var shapeEx = temp.Tag as ShapeEx;
                                if (shapeEx.Mark.Id == gmark.Id)
                                {
                                    circle = temp;
                                }
                            }
                            if (bool.Parse(e1.Result))
                            {
                                if (circle != null)
                                {
                                    this.map.RemoveOverlay(circle); ;
                                    this.overList.Remove(gmark);
                                }
                            }

                        });
                    });
            }
        }

        private void btnPlans_Click(object sender, RoutedEventArgs e)
        {
            FrmTask frmTask = new FrmTask();
            frmTask.Show();
        }

        private void btnSearch_Click(object sender, RoutedEventArgs e)
        {
            if (this.cmbUser.SelectedIndex < 0)
            {
                MsgHelper.Show("请选择一个用户");
                return;
            }
            if (this.dateGTimeStamp.SelectedDate == null)
            {
                MsgHelper.Show("请选择一个日期");
                return;
            }

            GUser user = this.cmbUser.SelectedValue as GUser;
            DateTime date = this.dateGTimeStamp.SelectedDate.Value;
            DataHelper.LoadUserLocationByDate(user.Id.ToString(), date, (result) =>
            {
                this.Dispatcher.BeginInvoke(() =>
                   {
                       map.CloseTip();
                       var marker = map.GetOverlaysByType(MOverlayType.MMarker);
                       List<MOverlay> listNew = new List<MOverlay>();
                       foreach (var item in marker)
                       {
                           this.map.RemoveOverlay(item); ;
                       }
                      
                       //map.GetOverlaysByType(MOverlayType.MMarker).to
                       //while (map.GetOverlaysByType(MOverlayType.MMarker).Count > 0)
                       //{
                       //    map.GetOverlaysByType(MOverlayType.MMarker).RemoveAt(0);
                       //}
                       var locations = new List<GLocation>();
                       foreach (var item in result)
                       {
                           locations.Add(item.Location);
                       }

                       if (result.Count == 0)
                       {
                           return;
                       }
                       else if (result.Count == 1)
                       {
                           MoveTo(locations[0].Location.Longitude, locations[0].Location.Latitude, 15);
                       }
                       else
                       {
                           MLngLatBounds bounds = SetExtent(locations, true);
                           map.LngLatBounds = bounds;
                           int zoom2 = MapHelper.GetZoom(bounds.NorthEast, bounds.SouthWest);
                           map.SetZoomAndCenter(zoom2, MapHelper.GetCenter(bounds.NorthEast, bounds.SouthWest));

                       }

                       foreach (var item in locations)
                       {
                           DrawImage(item);
                       }
                   });
            });
        }


        private MLngLatBounds SetExtent(IList<GLocation> list, bool hasBuffer)
        {
            var location = list[0].Location;
            double east = location.Longitude;
            double west = location.Longitude;
            double south = location.Latitude;
            double north = location.Latitude;
            foreach (var item in list)
            {
                var locationItem = item.Location;
                #region
                if (locationItem.Longitude < west)
                {
                    west = locationItem.Longitude;
                }
                if (locationItem.Longitude > east)
                {
                    east = locationItem.Longitude;
                }
                if (locationItem.Latitude < south)
                {
                    south = locationItem.Latitude;
                }
                if (locationItem.Latitude > north)
                {
                    north = locationItem.Latitude;
                }
                #endregion
            }
            if (hasBuffer)
            {
                int zoom = MapHelper.GetZoom(new MLngLat(west, south), new MLngLat(east, north));
                return new MLngLatBounds(west - MapHelper.GetBuffer(zoom), south - MapHelper.GetBuffer(zoom), east + MapHelper.GetBuffer(zoom), north + MapHelper.GetBuffer(zoom));
            }
            else
            {
                return new MLngLatBounds(west, south, east, north);
            }
        }

        private void MoveTo(double longtitude, double latitude, int zoom)
        {

            map.SetZoomAndCenter(zoom, new MLngLat(longtitude, latitude));
        }
        private void btnWorkItemType_Click(object sender, RoutedEventArgs e)
        {
            FrmWorkItemType frmWorkItemType = new FrmWorkItemType();
            frmWorkItemType.Show();
        }

        private void DrawImage(GLocation address)
        {
            MLngLat mpoint = new MLngLat(G.CLongitude(address.Location.Longitude), G.CLatitude(address.Location.Latitude));
            MMarker marker = new MMarker(mpoint)
            {

                IconURL = PathHelper.GetBasePath() + "images/lan_1.png",
                IconWidth = 23,
                IconHeight = 32,
                CanShowTip = true,
                Tag = new ShapeEx()
                {
                    ShapeType = GShapeType.UserMark
                },
                Tip = new MTip()
                {
                    Title = "标题:" + address.Title,
                    Content = "时间:" + address.GTimeStamp.ToString("yyyy-MM-dd HH:mm") + "\n位置:\n" + mpoint.X + "\n" + mpoint.Y,
                    Width = 200,
                    Height = 150
                }
            };
            map.AddOverlay(marker);
        }

        private void btnSearchTable_Click(object sender, RoutedEventArgs e)
        {
            FrmSearchTable frmSearchTable = new FrmSearchTable();
            if (this.cmbUser.SelectedIndex < 0)
            {
                MsgHelper.Show("请选择一个用户");
                return;
            }
            if (this.dateGTimeStamp.SelectedDate == null)
            {
                MsgHelper.Show("请选择一个日期");
                return;
            }

            GUser user = this.cmbUser.SelectedValue as GUser;
            DateTime date = this.dateGTimeStamp.SelectedDate.Value;
            frmSearchTable.SetUserId(user.Id, date);
            frmSearchTable.Show();
        }

    }// end for class

    public class ShapeEx
    {
        public bool IsAddEvent { get; set; }
        public GMark Mark { get; set; }
        public GShapeType ShapeType { get; set; }
    }// end for class
    public enum GShapeType
    {
        UserMark = 0,
        Circle = 1,
    }
}
